package cn.hznc.controller.service.toolAnalyze;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hznc.domain.entity.*;
import cn.hznc.domain.request.toolAnalyze.WarehouseUsageAnalyzeReq;
import cn.hznc.domain.response.PageResult;
import cn.hznc.mapper.EntryExitRecordMapper;
import cn.hznc.mapper.ToolForkInfoMapper;
import cn.hznc.mapper.ToolPartMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WarehouseUsageAnalyzeService {
    @Resource
    private EntryExitRecordMapper entryExitRecordMapper;
    @Resource
    private ToolPartMapper toolPartMapper;
    @Resource
    private ToolForkInfoMapper toolForkInfoMapper;
    @Transactional
    public PageResult<WarehouseUsageAnalyzeEntity> queryWarehouseUsageAnalyze(WarehouseUsageAnalyzeReq warehouseUsageAnalyzeReq){
        List<Integer> integers = new ArrayList<>();
        int flag=0;
        int startPage = (warehouseUsageAnalyzeReq.getPageNo()-1)* warehouseUsageAnalyzeReq.getPageSize();
        int endPage = warehouseUsageAnalyzeReq.getPageNo()* warehouseUsageAnalyzeReq.getPageSize();
        LambdaQueryWrapper<EntryExitRecordEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (CollectionUtil.isNotEmpty(warehouseUsageAnalyzeReq.getWarehouseType())){
            warehouseUsageAnalyzeReq.getWarehouseType().forEach(s -> {
                lambdaQueryWrapper.or().eq(EntryExitRecordEntity::getWarehouseId,s);
            });
        }
        if (warehouseUsageAnalyzeReq.getStartTime()!=null&&warehouseUsageAnalyzeReq.getEndTime()!=null){
            if (warehouseUsageAnalyzeReq.getStartTime().equals(warehouseUsageAnalyzeReq.getEndTime())){
                Date date = warehouseUsageAnalyzeReq.getEndTime();
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(date);
                calendar.add(Calendar.DATE, 1);
                date = calendar.getTime();
                warehouseUsageAnalyzeReq.setEndTime(date);
            }
            lambdaQueryWrapper.between(EntryExitRecordEntity::getCreateTime,warehouseUsageAnalyzeReq.getStartTime(),warehouseUsageAnalyzeReq.getEndTime());
//                lambdaQueryWrapper.gt(AbutmentOrderEntity::getReleaseTime, LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
        }else {
            lambdaQueryWrapper.between(EntryExitRecordEntity::getCreateTime, LocalDate.now().minusMonths(1),LocalDate.now());
        }
        lambdaQueryWrapper.ne(EntryExitRecordEntity::getPartno,"");
        lambdaQueryWrapper.ne(EntryExitRecordEntity::getWarehouseName,"");
        List<EntryExitRecordEntity> entryExitRecordEntityList = entryExitRecordMapper.selectList(lambdaQueryWrapper);
        Map<String,List<EntryExitRecordEntity>> map = entryExitRecordEntityList.stream().collect(Collectors.groupingBy(EntryExitRecordEntity::getPartno));
        List<WarehouseUsageAnalyzeEntity> warehouseUsageAnalyzeEntityList = new ArrayList<>();
        Iterator<Map.Entry<String,List<EntryExitRecordEntity>>> entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, List<EntryExitRecordEntity>> entry = entries.next();
//            if (CollectionUtil.isNotEmpty(toolPartEntityList)){
//                toolPartEntityList.forEach(toolPartEntity -> {
//                    if (StringUtils.isNotEmpty(toolPartEntity.getIdnr())&&StringUtils.isEmpty(warehouseUsageAnalyzeEntity.getIndr())){
//                        warehouseUsageAnalyzeEntity.setIndr(toolPartEntity.getIdnr());
//                    }
//                });
//            }
            Map<String,List<EntryExitRecordEntity>> map2 =entry.getValue().stream().collect(Collectors.groupingBy(EntryExitRecordEntity::getWarehouseName));
            Iterator<Map.Entry<String,List<EntryExitRecordEntity>>> entries1 = map2.entrySet().iterator();
            integers.add(map2.size());
            if (warehouseUsageAnalyzeEntityList.size()<warehouseUsageAnalyzeReq.getPageSize()){
                while (entries1.hasNext()){
                    Map.Entry<String, List<EntryExitRecordEntity>> entry1 = entries1.next();
                    if(flag<endPage)
                    {
                        flag++;
                    }else {break;}
                    if (flag>startPage){
                        String partno = entry.getKey();
                        LambdaQueryWrapper<ToolForkInfoEntity> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                        lambdaQueryWrapper1.eq(ToolForkInfoEntity::getPartno,partno);
                        ToolForkInfoEntity toolPartEntity = toolForkInfoMapper.selectOne(lambdaQueryWrapper1);
                        WarehouseUsageAnalyzeEntity warehouseUsageAnalyzeEntity = new WarehouseUsageAnalyzeEntity();

//                warehouseNameList.add(entries1.next().getKey());
//                        if (CollectionUtil.isNotEmpty(toolPartEntityList)){
//                            toolPartEntityList.forEach(toolPartEntity -> {
                        if (ObjectUtil.isNotEmpty(toolPartEntity)){
                            if (StringUtils.isNotEmpty(toolPartEntity.getIdnr())){
                                warehouseUsageAnalyzeEntity.setIndr(toolPartEntity.getIdnr());

                            }
                            if (ObjectUtil.isNotNull(toolPartEntity.getPrice()))
                                warehouseUsageAnalyzeEntity.setPrice(toolPartEntity.getPrice()*entry.getValue().size());
                        }
//                            });
//                        }
                        warehouseUsageAnalyzeEntity.setToolPlace(entry1.getKey());
                        warehouseUsageAnalyzeEntity.setPartno(partno);
                        LambdaQueryWrapper<ToolForkInfoEntity> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
                        lambdaQueryWrapper2.eq(ToolForkInfoEntity::getPartno,partno);
                        ToolForkInfoEntity toolForkInfoEntity = toolForkInfoMapper.selectOne(lambdaQueryWrapper2);
                        if (toolForkInfoEntity != null){
                            warehouseUsageAnalyzeEntity.setPartType(toolForkInfoEntity.getPartType());
                        }

                        Map<String,List<EntryExitRecordEntity>> map1 = entry1.getValue().stream().collect(Collectors.groupingBy(EntryExitRecordEntity::getType));
                        if (CollectionUtil.isNotEmpty(map1)){
                            try {
                                warehouseUsageAnalyzeEntity.setInboundNum(map1.get("inbound").stream().collect(Collectors.summingInt(EntryExitRecordEntity::getNumber)));
                            }catch (Exception e){ }
                            try {
                                warehouseUsageAnalyzeEntity.setOutboundNum(map1.get("outbound").stream().collect(Collectors.summingInt(EntryExitRecordEntity::getNumber)));
//                                if (map1.get("outbound").stream().collect(Collectors.summingInt(EntryExitRecordEntity::getNumber))>0){
//                                    List<BigDecimal> doubles = new ArrayList<>();
//                                    map1.get("outbound").forEach(a -> {
//                                        if (a.getPrice()!=null){
//                                            doubles.add(a.getPrice());
//                                        }
//                                    });
////                        Optional optional = doubles.stream().reduce(BigDecimal::add);
////                        map1.get("outbound").stream().collect(Collectors.s(People::getMoney))
////                        BigDecimal bigDecimal = map1.get("outbound").stream().map(EntryExitRecordEntity::getPrice).reduce(BigDecimal.ZERO,BigDecimal::add);
//                                    if (CollectionUtil.isNotEmpty(doubles))
//                                        warehouseUsageAnalyzeEntity.setPrice(doubles.stream().reduce(BigDecimal.ZERO,BigDecimal::add));
//                                }
                            }catch (Exception e){ }
                        }
                        warehouseUsageAnalyzeEntityList.add(warehouseUsageAnalyzeEntity);
                    }


                }

            }

        }
        PageInfo<WarehouseUsageAnalyzeEntity> result = new PageInfo<>(warehouseUsageAnalyzeEntityList);
        return new PageResult<>(result.getList(), (long)integers.stream().reduce(Integer::sum).orElse(0));

    }
}
